<!-- src/components/TagSelector.vue -->
<template>
  <div class="tag-selector">
    <el-select
      v-model="selectedTagIds"
      multiple
      filterable
      allow-create
      default-first-option
      :placeholder="placeholder"
      @change="handleTagChange"
    >
      <el-option
        v-for="tag in availableTags"
        :key="tag.id"
        :label="tag.name"
        :value="tag.id"
      />
    </el-select>
    
    <div class="selected-tags" v-if="selectedTags.length > 0">
      <el-tag
        v-for="tag in selectedTags"
        :key="tag.id"
        closable
        @close="removeTag(tag.id)"
        type="info"
        style="margin: 0.25rem;"
      >
        {{ tag.name }}
      </el-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { Tag } from '../types/models';

// 定义props
interface Props {
  modelValue?: number[];
  availableTags?: Tag[];
  placeholder?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  availableTags: () => [],
  placeholder: '选择或添加标签'
});

// 定义事件
const emit = defineEmits<{
  'update:modelValue': [value: number[]];
}>();

// 本地选择的标签ID
const selectedTagIds = ref<number[]>([...props.modelValue]);

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  selectedTagIds.value = [...newVal];
});

// 已选择的标签对象
const selectedTags = computed(() => {
  return props.availableTags.filter(tag => 
    selectedTagIds.value.includes(tag.id)
  );
});

// 处理标签选择变化
const handleTagChange = (value: number[]) => {
  selectedTagIds.value = value;
  emit('update:modelValue', value);
};

// 移除标签
const removeTag = (tagId: number) => {
  const index = selectedTagIds.value.indexOf(tagId);
  if (index > -1) {
    selectedTagIds.value.splice(index, 1);
    emit('update:modelValue', selectedTagIds.value);
  }
};
</script>

<style scoped>
.tag-selector {
  width: 100%;
}

.selected-tags {
  margin-top: 0.5rem;
  display: flex;
  flex-wrap: wrap;
}
</style>